import re

from django.utils import timezone
from rest_framework import serializers
from rest_framework.validators import UniqueValidator

from .models import User
from ..OrderManagement.models import UserPackage
from ..PackageManagement.serializers import PackageSerializer


class UserRegistrationSerializer(serializers.ModelSerializer):
    confirm_password = serializers.CharField(write_only=True, help_text='确认密码')

    username = serializers.CharField(
        min_length=8,
        max_length=50,
        validators=[UniqueValidator(queryset=User.objects.all(), message="用户名已存在")],
        help_text='用户名'
    )
    email = serializers.EmailField(
        validators=[UniqueValidator(queryset=User.objects.all(), message="邮箱已存在")],
        help_text='邮箱'
    )
    password = serializers.CharField(
        min_length=8,
        max_length=50,
        write_only=True,
        help_text='密码'
    )

    class Meta:
        model = User
        fields = ('username', 'email', 'password', 'confirm_password')
        extra_kwargs = {
            'password': {'write_only': True},
        }

    def validate_email(self, value):
        # 验证邮箱必须为@*.*形式
        pattern = r'^.+@.+\..+$'
        if not re.match(pattern, value):
            raise serializers.ValidationError("邮箱格式不正确")
        return value

    def validate(self, data):
        if data['password'] != data['confirm_password']:
            raise serializers.ValidationError("密码和确认密码不一致")
        return data

    def create(self, validated_data):
        validated_data.pop('confirm_password')
        user = User(
            username=validated_data['username'],
            email=validated_data['email'],
            user_type=0,  # 默认普通用户
            status=True  # 默认激活状态
        )
        user.set_password(validated_data['password'])
        user.save()
        return user


class UserCreateSerializer(serializers.ModelSerializer):
    user_type = serializers.ChoiceField(choices=User.USER_TYPE, default=0, help_text='用户类型')
    username = serializers.CharField(
        min_length=8,
        max_length=50,
        validators=[UniqueValidator(queryset=User.objects.all(), message="用户名已存在")],
        help_text='用户名'
    )
    email = serializers.EmailField(
        validators=[UniqueValidator(queryset=User.objects.all(), message="邮箱已存在")],
        help_text='邮箱'
    )
    password = serializers.CharField(
        min_length=8,
        max_length=50,
        write_only=True,
        help_text='密码'
    )

    def validate_email(self, value):
        # 验证邮箱必须为@*.*形式
        pattern = r'^.+@.+\..+$'
        if not re.match(pattern, value):
            raise serializers.ValidationError("邮箱格式不正确")
        return value

    class Meta:
        model = User
        fields = ('username', 'password', 'user_type', 'status', 'phone', 'email')
        extra_kwargs = {
            'password': {'write_only': True},
        }

    def create(self, validated_data):
        # 弹出密码，使用 set_password 处理加密
        password = validated_data.pop('password')
        user = User(**validated_data)
        user.set_password(password)
        user.save()
        return user


class UserUpdateSerializer(serializers.ModelSerializer):
    username = serializers.CharField(
        min_length=8,
        max_length=50,
        validators=[UniqueValidator(queryset=User.objects.all(), message="用户名已存在")],
        help_text='用户名'
    )
    email = serializers.EmailField(
        validators=[UniqueValidator(queryset=User.objects.all(), message="邮箱已存在")],
        help_text='邮箱'
    )
    password = serializers.CharField(
        min_length=8,
        max_length=50,
        write_only=True,
        help_text='密码'
    )

    def validate_email(self, value):
        # 验证邮箱必须为@*.*形式
        pattern = r'^.+@.+\..+$'
        if not re.match(pattern, value):
            raise serializers.ValidationError("邮箱格式不正确")
        return value

    class Meta:
        model = User
        fields = ('username', 'password', 'user_type', 'status', 'phone', 'email')
        extra_kwargs = {
            'password': {'write_only': True, 'required': False},
        }

    def update(self, instance, validated_data):
        password = validated_data.pop('password', None)
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        if password:
            instance.set_password(password)
        instance.save()
        return instance


class UserListSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'user_type', 'status', 'phone', 'email', 'create_time', 'update_time', 'last_login')


class UserSerializer(serializers.ModelSerializer):
    dynamic_status = serializers.SerializerMethodField()
    package_name = serializers.SerializerMethodField()
    expiration_time = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'dynamic_status', 'package_name', 'expiration_time')

    def get_userpackage(self, obj):
        # 假设每个用户始终只有一条套餐记录，可以直接取第一条
        return obj.packages.first()

    def get_dynamic_status(self, obj):
        userpackage = self.get_userpackage(obj)
        if userpackage:
            current_time = timezone.now()
            if userpackage.status == 'disabled' or userpackage.expiration_time < current_time:
                return userpackage.status
            return obj.status  # 返回用户状态
        return obj.status

    def get_package_name(self, obj):
        userpackage = self.get_userpackage(obj)
        return userpackage.package.name if userpackage else None

    def get_expiration_time(self, obj):
        userpackage = self.get_userpackage(obj)
        return userpackage.expiration_time if userpackage else None


class UserPackageSerializer(serializers.ModelSerializer):
    package = PackageSerializer()

    class Meta:
        model = UserPackage
        fields = ('package', 'cost', 'status', 'subscription_time', 'expiration_time')


class UserInfoSerializer(serializers.ModelSerializer):
    # 通过 related_name "packages" 获取用户的所有套餐记录
    packages = UserPackageSerializer(many=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'phone', 'user_type', 'status', 'create_time', 'update_time', 'packages')